import { createRouter, createWebHashHistory } from 'vue-router';

const { api } = window;
const Home = () => import('../components/Home.vue');
const Login = () => import('../components/Login.vue');
const Register = () => import('../components/Register.vue');
const DiscoverPage = () => import('../components/Pages/DiscoverPage.vue');
const RecommendPage = () => import('../components/Pages/RecommendPage.vue');
const PlaylistDetail = () => import('../components/Pages/PlaylistDetail.vue');

const routes = [
	{
		path: '/',
		name: 'home',
		component: Home,
		redirect: '/discover',
		children: [
			{
				path: '/discover',
				name: 'discover',
				component: DiscoverPage
			},
			{
				path: '/recommend',
				name: 'recommend',
				component: RecommendPage
			},
			{
				path: '/playlist/:id',
				name: 'playlist',
				component: PlaylistDetail
			},
			{
				path: '/recent',
				name: 'recent',
				component: () => import('../components/Pages/ComingSoon.vue')
			},
			{
				path: '/favorite',
				name: 'favorite',
				component: () => import('../components/Pages/ComingSoon.vue')
			},
			{
				path: '/local',
				name: 'local',
				component: () => import('../components/Pages/ComingSoon.vue')
			},
			{
				path: '/download',
				name: 'download',
				component: () => import('../components/Pages/ComingSoon.vue')
			}
		],
	},
	{
		path: '/login',
		name: 'login',
		component: Login,
	},
	{
		path: '/register',
		name: 'register',
		component: Register,
	},
];
const router = createRouter({
	history: createWebHashHistory(),
	routes,
});
// 路由守卫 - 允许未登录用户访问登录页和注册页
router.beforeEach(async (to, _from, next) => {
	// 白名单：不需要登录即可访问的页面
	const whiteList = ['login', 'register'];
	if (!whiteList.includes(to.name as string) && (await api.getStoreData()) === undefined) {
		next({ name: 'login' });
	} else {
		next();
	}
});

export default router;
